<?php


namespace app\index\controller;
use app\common\model\User as UserModel;
use app\common\model\Userinfo;
use app\common\model\Userinfo as UserInfoModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Sell as SellModel;
use app\common\model\Produce as ProduceModel;
use think\helper\Arr;
use think\Loader;
use think\Request;
use think\Db;
use think\Session;

use think\Controller;

class Company extends Controller
{
    /** 主页 */
    public function home(){
        $cID = Session::get('uID');

        /** 四个便签 **/
        $goods_num = Db::query("select count(*) num from goods where cID=$cID")[0]['num'];
        $produce_num = Db::query("select sum(gNum) num from produce where gID in (select gID from goods where cID=$cID)")[0]['num'];
        $sell_num = Db::query("select count(*) num from sell where pID in (select pID from produce where gID in (select gID from goods where cID=$cID))")[0]['num'];
        $sell_price = Db::query("select sum(uPrice) price from sell where pID in (select pID from produce where gID in (select gID from goods where cID=$cID))")[0]['price'];
        if (!$produce_num) $produce_num = 0;
        if (!$sell_price) $sell_price = 0;
        $this->assign([
           'goods_num' => $goods_num,
           'produce_num' => $produce_num,
            'sell_num' => $sell_num,
            'sell_price' => $sell_price
        ]);

        /** 图表数据 */
        $year = date('Y'); //获取当前年份
        //分月 销售总额
        $temp_list = Db::query("select date_format(uRDate,'%m') mon,sum(uPrice) price from sell where pID in (select pID from produce where gID in (select gID from goods where cID=:cID)) and date_format(uRDate,'%Y')=:year and uTrack='已完成' group by mon"
            ,['cID'=>$cID, 'year'=>$year]);
        $len = count($temp_list); //获得数组长度
        $price_total = [];//用来存放各月总数
//        dump($temp_total);
        //为$price_total赋值
        for ($i=0,$j=0;$i<12;$i++) {
            if ($j < $len) {
                if (($i+1) == (int)$temp_list[$j]['mon']) { //arr[0]==1月总数，以此类推
                    $price_total[$i] = (float)$temp_list[$j]["price"];
                    $j = $j + 1;
                } else {
                    $price_total[$i] = 0.0;
                }
            }else{
                $price_total[$i] = 0.0;
            }
        }
        //分月 订单成交量
        $temp_list = Db::query("select date_format(uRDate,'%m') mon,count(*) num from sell where pID in (select pID from produce where gID in (select gID from goods where cID=:cID)) and date_format(uRDate,'%Y')=:year group by mon"
            ,['cID'=>$cID, 'year'=>$year]);
        $len = count($temp_list); //获得数组长度
        $sell_total = [];//用来存放各月总数
//        dump($temp_total);
        //为$price_total赋值
        for ($i=0,$j=0;$i<12;$i++) {
            if ($j < $len) {
                if (($i+1) == (int)$temp_list[$j]['mon']) { //arr[0]==1月总数，以此类推
                    $sell_total[$i] = (int)$temp_list[$j]["num"];
                    $j = $j + 1;
                } else {
                    $sell_total[$i] = 0;
                }
            }else{
                $sell_total[$i] = 0;
            }
        }

        $this->assign([
            'price_total' => $price_total,
            'sell_total' => $sell_total,
        ]);

        return $this->fetch();
    }

    /* 未审批或审批失败企业 */
    public function otherHome(){
        $cID = Session::get('uID');
        // 刷新时判断是否已审批
        $cVerify = Db::query("select cVerify from company where cID=$cID")[0]['cVerify'];
        if($cVerify == 1){
            Session::set('cVerify',$cVerify);
            return $this->redirect('home');
        } else{
            Session::set('cVerify',$cVerify);
            return $this->fetch();
        }
    }
    /* 返回企业信息 */
    public function getCompany(){
        $cID = Session::get('uID');
        $one = Db::query("select * from company where cID=$cID")[0];
        return json($one);
    }
    /* 企业修改信息重新申报 */
    public function editCompany(){
        $data = $this->request->post();
        $data['uID'] = $data['cID'];
        $data['cVerify'] = 2;
        $company = new CompanyModel();
        $userinfo = new UserInfoModel();
        $company->allowField(true)->isUpdate(true)->save($data);
        $userinfo->allowField(true)->isUpdate(true)->save($data);
        Session::set('cVerify',2);
        Session::set('name',$data['name']);
        $result['success'] = "true";
        return $result;
    }

    /** 主页结束 */

    /** 产品管理页面 */
    public function goods(){
        return $this->fetch();
    }

    /* 新增产品 */
    public function addGoods(){
        $data = $this->request->post();
        $file = request()->file('gImg');
        $cID = Session::get('uID');
        $data['cID'] = $cID;
        $goods = new GoodsModel();

        //销售码和二维码
        $code = $this->qrcode();
        $data['gSellCode'] = $code['gSellCode'];
        $data['gSellCodeImg'] = $code['gSellCodeImg'];

        //产品图
        if($file){
            // 指定规则  其中md5和sha1规则会自动以散列值的前两个字符作为子目录，后面的散列值作为文件名。
            // 保存路径 public/uploads/goodsImg
            $info = $file->rule('md5')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'goodsImg');
            if($info){
                //保存 子目录/文件名
                $img_url = $info->getSaveName();
                $data['gImg'] = $img_url;
                $goods->allowField(true)->save($data);
                $result['success'] = "true";
                return $result;
            }
        }

    }

    /* 生成销售码和产品二维码 */
    public function qrcode(){
        Loader::import('qrcode.phpqrcode',EXTEND_PATH, '.php');
        $gSellCode = date('dHis').time().rand(10000,9999999); //产品销售码
        $value = "产品销售码为：".$gSellCode;//二维码内容
//        $value = "22222222222";//二维码内容
//        dump($value);
        $matrixPointSize = 10;
        $errorCorrectionLevel = 'H';  //容错级别
        $margin=2;
        //生成二维码图片
        //设置二维码文件名
        $head_path = ROOT_PATH. 'public' . DS . 'uploads';
        $filename = 'gSellCodeImg'. DS .time().rand(1000,99999).'.png'; //存入数据库的文件名
        $img_path = $head_path . DS . $filename;
//        dump($filename);
        //生成二维码
        \QRcode::png($value, $img_path ,$errorCorrectionLevel, $matrixPointSize, $margin);

        //以下是二维码中带上logo,根据需要使用
        $logo = ROOT_PATH. DS .'public/static/img/logo.jpeg';//准备好的logo图片
        $QR = $img_path;//已经生成的原始二维码图
        if ($logo !== FALSE) {
            $QR = imagecreatefromstring(file_get_contents($QR));
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);//二维码图片宽度
            $QR_height = imagesy($QR);//二维码图片高度
            $logo_width = imagesx($logo);//logo图片宽度
            $logo_height = imagesy($logo);//logo图片高度
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width/$logo_qr_width;
            $logo_qr_height = $logo_height/$scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
                $logo_qr_height, $logo_width, $logo_height);
        }
        imagepng ($QR, $img_path );//重新生成二维码图片
        $data['gSellCode'] = $gSellCode;
        $data['gSellCodeImg'] = $filename;
        return $data; //返回的数据
    }

    /* 删除选中产品 */
    public function doDelete(){
        $data = $this->request->post()['ids'];
        $ids = explode(',',$data);
        Db::table('goods')->delete($ids);
        $result['success'] = "true";
        return $result;
    }

    /* 修改产品图片 */
    public function goodsImg(){
        $data = $this->request->post();
        // 获取表单上传文件
        $file = request()->file('gImg');
        $goods = new GoodsModel();
        if($file){
            // 指定规则  其中md5和sha1规则会自动以散列值的前两个字符作为子目录，后面的散列值作为文件名。
            // 保存路径 public/uploads/goodsImg
            $info = $file->rule('md5')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'goodsImg');
            if($info){
                //保存 子目录/文件名
                $img_url = $info->getSaveName();
                $data['gImg'] = $img_url;
                $goods->allowField(true)->isUpdate(true)->save($data);
                $result['success'] = "true";
                return $result;
            }
        }
    }

    /* 获取产品信息 */
    public function getDataList(){
        $cID = Session::get('uID');
        $List = Db::query("select * from goods where cID=:cID",['cID'=>$cID]);
        return json($List);
    }

    /* 修改产品信息 */

    public function editGoods(){
        $data = $this->request->post();
        $goods = new GoodsModel();
//        dump($data);
        $goods->allowField(true)->isUpdate(true)->save($data);
        $result['success'] = "true";
        return $result;
    }

    /** 产品管理页面结束 */

    /** 生产管理页面 */

    public function produce(){
        $cID = Session::get('uID');
        $gID_list = Db::query("select gID,gName from goods where cID=:cID",['cID'=>$cID]);
        $this->assign('gID_list',$gID_list);
        return $this->fetch();
    }

    //获取生产表格数据
    public function getProduceDataList(){
        $cID = Session::get('uID');
        $aList = Db::query("select p.*, g.gName, g.gImg from produce p join goods g using(`gID`) where gID in (select gID from goods where cID=:cID)",['cID'=>$cID]);
        return json($aList);
    }

    // 新增生产
    public function addProduce(){
        $data = $this->request->post();
        $produce = new ProduceModel();
        $produce->allowField(true)->save($data);
        $result['success'] = "true";
        return $result;
    }

    //删除生产
    public function doProduceDelete(){
        $data = $this->request->post()['ids'];
        $ids = explode(',',$data);
        Db::table('produce')->delete($ids);
        $result['success'] = "true";
        return $result;
    }


    /** 生产管理页面结束 */

    /** 销售管理 */

    public function sell(){
        return $this->fetch();
    }

    //返回表格数据
    public function getSellDataList(){
        $cID = Session::get('uID');
        $List = Db::query("select * from sell where pID in (select pID from produce where gID in (select gID from goods where cID=$cID))");
        // 改变原数组需要加 & 表示引用，否则原数组不变
        foreach ($List as &$item){
            $item['gName'] = Db::query("select gName from goods where gID=(select gID from produce where pID=:pID)",['pID' => $item['pID']])[0]['gName'];
            $item['gImg'] = Db::query("select gImg from goods where gID=(select gID from produce where pID=:pID)",['pID' => $item['pID']])[0]['gImg'];
        }

        return json($List);
    }

    /** 销售管理结束 */

}